package com.zyh.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.json.User;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

/**
 * @Author zyh
 * @Date 2024/8/13 16:32
 * @Description
 *
 * 1.创建User对象
 * 2.获取Jackson的操作对象
 * 3.将user对象转为String
 * 4.将user对象写入文件中
 * 5.将user对象写入字节数组
 * 6.将json字符串str转为User对象
 * 7.将json文件中的json字符串读入程序中并转为User
 * 8.将字节数组bytes中的内容转化为User
 */

public class JacksonDemo1 {
    public static void main(String[] args) throws IOException {
        //创建User对象
        User user = new User("zyh", 20, new Date());
        //获取Jackson的操作对象
        ObjectMapper mapper = new ObjectMapper();
        //将user对象转为String
        String str = mapper.writeValueAsString(user);
        //将user对象写入文件中
        mapper.writeValue(new File("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day15-code\\src\\com\\zyh\\jackson\\jackson.json"),user);
        //将user对象写入字节数组
        byte[] bytes = mapper.writeValueAsBytes(user);
        System.out.println(Arrays.toString(bytes));
        //将json字符串str转为User对象
        User user1 = mapper.readValue(str, User.class);
        System.out.println("user1 = " + user1);
        //将json文件中的json字符串读入程序中并转为User
        User user2 = mapper.readValue(new File("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day15-code\\src\\com\\zyh\\jackson\\jackson.json"), User.class);
        System.out.println("user2 = " + user2);
        //将字节数组bytes中的内容转化为User
        User user3 = mapper.readValue(bytes, User.class);
        System.out.println("user3 = " + user3);

    }
}
